package com.tyq.auth.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tyq.auth.common.ResultData;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义注销登录处理器
 *
 * @author 谭永强
 * @date 2024-05-20
 **/
@Component
public class MyLogoutSuccessHandler implements LogoutSuccessHandler {

    @Resource
    private ObjectMapper objectMapper;
    @Resource
    private TokenStore tokenStore;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        String authorization = request.getHeader("Authorization");
        ResultData<Authentication> resultData = new ResultData<>();
        if(!ObjectUtils.isEmpty(authorization)){
            authorization = authorization.substring(7);
            OAuth2AccessToken accessToken = tokenStore.readAccessToken(authorization);
            if(!ObjectUtils.isEmpty(accessToken)){
                tokenStore.removeAccessToken(accessToken);
                tokenStore.removeRefreshToken(accessToken.getRefreshToken());
                tokenStore.removeAccessTokenUsingRefreshToken(accessToken.getRefreshToken());
            }
        }
        resultData.setSuccess(true);
        resultData.setMessage("注销成功");
        resultData.setResult(authentication);
        objectMapper.writeValue(response.getOutputStream(), resultData);
    }

}
